package com.order.service.impl;

import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.order.mapper.ProductCategoryMapper;
import com.order.pojo.ProductCategory;
import com.order.pojo.ProductInfo;
import com.order.mapper.ProductInfoMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.order.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author llr
 * @since 2025-08-11
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements ProductInfoService {
    @Autowired
    ProductInfoMapper productInfoMapper;
    @Autowired
    ProductCategoryMapper productCategoryMapper;

    @Override
    public PageInfo<ProductInfo> selectpage(int pageNum, int pageSize, ProductInfo productInfo) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<ProductInfo>();

        // 优化：仅在 productName 有效时添加查询条件
        String productName = productInfo.getProductName();
        if (productName != null && !productName.trim().isEmpty()) {
            queryWrapper.like("product_name", productName);
        }
        queryWrapper.eq("del", 0);

        List<ProductInfo> list = productInfoMapper.selectList(queryWrapper);

        // 修复：处理关联查询的空指针问题
        for (ProductInfo lst : list) {
            Integer categoryType = lst.getCategoryType();
            if (categoryType == null) {
                lst.setCategoryName("未设置类目");
                continue;
            }

            ProductCategory productCategory = productCategoryMapper.selectById(categoryType);
            if (productCategory == null) {
                lst.setCategoryName("类目不存在");
            } else {
                lst.setCategoryName(productCategory.getCategoryName());
            }
        }

        return PageInfo.of(list);
    }
}
